package com.rocsun.order.service.impl;

import com.rocsun.order.Order;
import com.rocsun.order.service.OrderService;
import com.rocsun.product.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @program: rocsun-cloud-alibaba
 * @description:
 * @author: yx.guo
 * @create: 2025-08-28 10:50
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    @Override
    public Order createOrder(Long productId, Long userId) {
        Order order = new Order();
        order.setId(1L);

        // 计算总金额
        Product product = getProductFromRemote(productId);
        BigDecimal amount = product.getPrice().multiply(new BigDecimal(product.getNum()));

        order.setTotalAmount(amount);
        order.setUserId(userId);
        order.setNickName("龙舞");
        order.setAddress("郑州");
        order.setProductList(Arrays.asList(product));

        return order;
    }

    private Product getProductFromRemote(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;

        Product product = restTemplate.getForObject(url, Product.class);

        return product;
    }

}
